package src.leetcode.backtrack.medium_0047;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class permuteUnique {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.permuteUnique(new int[]{1,1,2}));
    }
}

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path;
    public List<List<Integer>> permuteUnique(int[] nums) {
        path = new ArrayList<>(nums.length);
        boolean []used = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(nums, used);
        return res;
    }

    private void dfs(int[] nums,boolean[] used){
        if(path.size() == used.length){
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = 0; i < nums.length; i++) {
            if(used[i]) continue;
            if(i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;

            path.add(nums[i]);
            used[i] = true;
            dfs(nums, used);
            used[i] = false;
            path.remove(path.size() - 1);
        }
    }
}
